import pandas as pd
from data_preparation import DataPreparator
from central_server import CentralServer
import threading
import time
import os
from cryptography.fernet import Fernet

def run_participant(file_path: str, format_rules: dict, fernet_key: bytes, host: str = 'localhost', port: int = 5000):
    """运行参与者节点"""
    preparator = DataPreparator(fernet_key)
    
    # 加载和准备数据
    data = preparator.load_and_prepare_data(file_path)
    print(f"已加载数据: {file_path}")
    
    # 加密数据
    encrypted_data = preparator.encrypt_data(data)
    print("数据已加密")
    
    # 提取元数据
    metadata = preparator.extract_metadata(data)
    print("元数据已提取")
    
    # 生成元数据哈希
    metadata_hash = preparator.hash_metadata(metadata)
    print("元数据哈希已生成")
    
    # 验证格式合规性
    compliance = preparator.verify_format_compliance(data, format_rules)
    print("格式合规性已验证")
    
    # 加密合规性结果
    encrypted_compliance = preparator.encrypt_compliance_results(compliance)
    print("合规性结果已加密")
    
    # 发送到中央服务器
    preparator.send_to_central_server(host, port, encrypted_data, metadata_hash, encrypted_compliance)
    print("数据已发送到中央服务器")

def run_central_server(fernet_key: bytes, encrypted_output: str = 'report.enc', 
                      plain_output: str = 'report.json'):
    """运行中央服务器"""
    server = CentralServer(fernet_key)
    
    # 启动服务器线程
    server_thread = threading.Thread(target=server.start_server)
    server_thread.start()
    
    # 等待所有参与者发送数据
    time.sleep(5)  # 在实际应用中，应该有更好的同步机制
    
    # 生成报告
    report = server.generate_global_report()
    print("全局报告已生成")
    
    # 签名报告
    signature = server.sign_report(report)
    print("报告已签名")
    
    # 加密并存储报告
    server.encrypt_and_store_report(report, signature, encrypted_output)
    print(f"加密报告已存储到: {encrypted_output}")
    
    # 生成不加密报告
    server.generate_plain_report(report, signature, plain_output)
    print(f"不加密报告已存储到: {plain_output}")

def main():
    # 定义格式规则
    format_rules = {
        'date': 'date',
        'temperature': 'numeric',
        'humidity': 'numeric',
        'wind_speed': 'numeric',
        'precipitation': 'numeric',
        'pressure': 'numeric',
        'weather_condition': 'string',
        'uv_index': 'numeric',
        'visibility': 'numeric',
        'cloud_cover': 'numeric',
        'air_quality_index': 'numeric'
    }
    
    # 确保数据目录存在
    os.makedirs('data', exist_ok=True)
    
    # 生成共享密钥
    fernet_key = Fernet.generate_key()
    
    # 启动中央服务器
    server_thread = threading.Thread(target=run_central_server, args=(fernet_key,))
    server_thread.start()
    
    # 等待服务器启动
    time.sleep(1)
    
    # 运行参与者
    participants = [
        ('data/weather_data.csv', format_rules),
        ('data/weather_extended.csv', format_rules)
    ]
    
    for file_path, rules in participants:
        participant_thread = threading.Thread(
            target=run_participant,
            args=(file_path, rules, fernet_key)
        )
        participant_thread.start()
        participant_thread.join()

if __name__ == "__main__":
    main() 